<template>
  <div>
    <contract-approve ref="approvalRef" :query-id="queryId" view-mode @get-data="handleGetData">
      <template v-for="p in busProcess">
        <tr :key="p.type">
          <td>
            <span>{{ p.signLabel }}意见</span>
            <span v-if="p.signOrg">
              <br />
              （{{ p.signOrg }}）
            </span>
          </td>
          <template v-if="!p.editable || viewMode">
            <td colspan="3">
              <div class="text-left">{{ approval[p.keys.comment] }}&nbsp;</div>
              <sign-panel
                :approval="approval"
                :sign-name="p.signName"
                :sign-date="p.keys.date"
              ></sign-panel>
            </td>
          </template>
          <template v-else>
            <td colspan="3" class="input-td">
              <el-input
                v-model="approval[p.keys.comment]"
                type="textarea"
                placeholder="请填写"
              ></el-input>
              <div class="row px-3 py-2">
                <div class="col text-left text-muted">签字：{{ editName }}</div>
                <div class="col text-left text-muted">日期：{{ editDate }}</div>
              </div>
            </td>
          </template>
        </tr>
      </template>
      <template>
        <tr>
          <td>省农担意见</td>
          <td colspan="3">
            <div v-for="(r, index) of records" :key="index" class="p-item">
              <record-item :record-data="r"></record-item>
            </div>
          </td>
        </tr>
      </template>
    </contract-approve>

    <div class="text-center" v-if="editable">
      <el-button
        type="primary"
        class="btn-long"
        :disabled="loading"
        :loading="saveLoading"
        @click="handleSuccessConfirm"
      >
        提交
      </el-button>
      <el-button class="btn-long" :disabled="loading" :loading="saveLoading" @click="handleDismiss">
        取消
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import RecordItem from '@/credit/views/county/unionProvince/components/projectApprove/RecordItem'

import {
  getAuthPerson,
  getApproval,
  approvalComment,
  getInProcess,
  getOutProcess,
  validateProcess,
} from '@/credit/views/county/unionProvince/components/contractApprove/index'

import ContractApprove from '@/credit/views/county/unionProvince/components/contractApprove/Base'
import SignPanel from '@/credit/views/county/unionProvince/components/contractApprove/SignPanel'

export default {
  components: {
    SignPanel,
    RecordItem,
    ContractApprove,
  },
  props: {
    queryId: {
      type: String,
      required: true,
    },
    viewMode: Boolean,
  },
  data() {
    return {
      loading: false,
      saveLoading: false,

      related: {},
      approval: {},
      solidApproval: {},

      busProcess: [],
      // 有权审批人
      authPerson: {},
      // 省担保风控部负责人
      riskManager: {},
      provinceTable: 'workflow_record',
      records: [],
    }
  },
  computed: {
    ...mapGetters(['user', 'org', 'job', 'userId']),
    editName() {
      return this.user.realName
    },
    editDate() {
      return this.$utils.dateFormat(new Date(), 'yyyy年MM月dd日')
    },
    editable() {
      return this.busProcess.some(it => it.editable)
    },

    // 合同审批表ID
    approvalId() {
      return this.approval.contract_approval_id
    },
    outProcess() {
      // +this.approval.res_corp_status === 1
      return +this.related.process_status === 1
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    getProvinceOption() {
      const key = 'CONTRACT_APPROVAL'
      this.$api
        .getData(this.$serviceName, 'workflow_record', {
          'workflow_key.eq': key,
          'task_id.eq': `''`,
          'wf_related_id.eq': this.queryId,
        })
        .then(res => {
          const data = res?.data ?? []
          this.records = data.map(this.dataAdaptor)
        })
    },
    dataAdaptor(item) {
      item.dateStr = this.$utils.dateFormat(item.approval_time, 'yyyy年MM月dd日')
      return item
    },
    handleSuccessConfirm() {
      const editProcess = this.busProcess.filter(it => it.editable)
      const errMsg = validateProcess(this.approval, editProcess)
      if (errMsg) {
        return this.$message.error(errMsg)
      }

      this.$utils
        .msgbox({
          message: '是否提交？',
          type: 'warning',
          beforeClose: () => this.updateApproval(editProcess),
        })
        .then(res => {
          this.$message.success('提交成功')
          this.$emit('success', res)
          this.refreshApproval()
        })
        .catch(err => {
          this.$message.error(`提交失败，请重试！`)
          throw new Error(err)
        })
    },

    // 更新合同审批内容
    updateApproval(bps) {
      if (!this.approvalId) {
        return this.$message.error('获取合同审批信息失败，不能提交')
      }

      return approvalComment(this.approvalId, bps, {
        name: this.editName,
        status: 1,
        approval: this.approval,
        solidApproval: this.solidApproval,
        queryId: this.queryId,
      })
    },

    handleDismiss() {
      this.$emit('dismiss', false)
    },

    getAuthPerson() {
      if (this.authPerson.userId) {
        return Promise.resolve()
      }

      return getAuthPerson().then(({ corp, riskManager }) => {
        this.authPerson = corp
        this.riskManager = riskManager
      })
    },

    refreshApproval() {
      return getApproval(this.queryId).then(approval => {
        this.approval = approval || {}
        this.solidApproval = { ...this.approval }
        this.doProcess()
      })
    },

    handleGetData({ related, approval }) {
      this.related = related || {}
      this.approval = approval || {}
      this.solidApproval = { ...this.approval }
      this.getAuthPerson().then(() => this.doProcess())
      this.getProvinceOption()
    },

    doProcess() {
      const { approval, related, authPerson, riskManager } = this
      const needData = {
        approval,
        related,
        authPerson,
        riskManager,
        user: this.user,
        org: this.org,
      }
      const processStatus = +related.process_status
      this.busProcess =
        processStatus === 0
          ? getInProcess(needData)
          : processStatus === 1
          ? getOutProcess(needData)
          : []
    },
  },
}
</script>

<style lang="scss" scoped></style>
